/*!
 * Main v1.0.0. 
 * 公用js
 */
//定于全局域名空间
var TuHao = window.TuHao || {};
TuHao.LoginUrl = "/th/login";
/** *****公用ajax，根据传递的type参数，确定是post or get请求******* */
TuHao.Ajax = new function () {
    var self = this;
    // post提交
    self.post = function (requestObject) {
        // 提交之前做一些事情:首先判断是否存在和是否是方法类别
        (requestObject.beforeCallback && typeof(requestObject.beforeCallback) === "function") && requestObject.beforeCallback();

        // 获取表单内容
        var formData = $("#" + requestObject.formId).serialize() + '&randomTime=' + (new Date()).getTime();
        $.ajax({
            type: "post",
            headers: {
                accept: "application/json; charset=utf-8"
            },
            url: requestObject.url || TuHao.LoginUrl,
            data: formData,
            dataType: "json",
            success: function (response) {
                if (response) {
                    if (response.status == 200) {
                        // 请求成功之后做一些事情:首先判断方法是否存在和是否是方法类别
                        (requestObject.successCallback && typeof(requestObject.successCallback) === "function") && requestObject.successCallback(response);
                    } else if (response.status == 401) { //登录请求
                        alert("请登录后操作");
                        window.location.href = TuHao.LoginUrl;
                    } else {
                        if (requestObject.errorCallback && typeof(requestObject.errorCallback) === "function") {
                            requestObject.errorCallback(response);
                        } else {
                            alert("解析错误处理错误，请求重新请求");
                            window.location.reload()
                        }
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert("服务器响应错误");
            }
        });
    };

    self.validPost = function (requestObject) {
        var object ={
            onValidationComplete:function(){
                // 提交之前做一些事情:首先判断是否存在和是否是方法类别
                (requestObject.beforeCallback && typeof(requestObject.beforeCallback) === "function") && requestObject.beforeCallback();

                // 获取表单内容
                var formData = $("#" + requestObject.formId).serialize() + '&randomTime=' + (new Date()).getTime();
                $.ajax({
                    type: "post",
                    headers: {
                        accept: "application/json; charset=utf-8"
                    },
                    url: requestObject.url || TuHao.LoginUrl,
                    data: formData,
                    dataType: "json",
                    success: function (response) {
                        if (response) {
                            if (response.status == 200) {
                                // 请求成功之后做一些事情:首先判断方法是否存在和是否是方法类别
                                (requestObject.successCallback && typeof(requestObject.successCallback) === "function") && requestObject.successCallback(response);
                            } else if (response.status == 401) { //登录请求
                                alert("请登录后操作");
                                window.location.href = TuHao.LoginUrl;
                            } else {
                                if (requestObject.errorCallback && typeof(requestObject.errorCallback) === "function") {
                                    requestObject.errorCallback(response);
                                } else {
                                    alert("解析错误处理错误，请求重新请求");
                                    window.location.reload()
                                }
                            }
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert("服务器响应错误");
                    }
                });
            },
            "alertType":requestObject.alertType
        };
        $("#" + requestObject.formId).TuHaoValid(object);
    };

    // get请求
    self.get = function (requestObject) {
        var formData;
        if (requestObject.formData) {
            formData = (requestObject.formData) + '&randomTime=' + (new Date()).getTime();
        } else {
            formData = 'randomTime=' + (new Date()).getTime();
        }
        //支持异步请求
        var async1 = true;
        if (requestObject.async != null && requestObject.async != null && typeof(requestObject.async) === "boolean") {
            if (!requestObject.async) {
                async1 = false;
            }
        }
        $.ajax({
            type: "get",
            url: requestObject.url || YueXiang.LoginUrl,
            data: formData,
            async: async1,
            headers: {
                accept: "application/json; charset=utf-8"
            },
            dataType: "json",
            success: function (response) {
                if (response) {
                    if (response.status == 200) {
                        // 请求成功之后做一些事情:首先判断方法是否存在和是否是方法类别
                        (requestObject.successCallback && typeof(requestObject.successCallback) === "function") && requestObject.successCallback(response);
                    } else if (response.status == 401) { //登录请求
                        alert("请登录后操作");
                        window.location.href = TuHao.LoginUrl;
                    } else {
                        if (requestObject.errorCallback && typeof(requestObject.errorCallback) === "function") {
                            requestObject.errorCallback(response);
                        } else {
                            alert("解析错误处理错误，请求重新请求");
                            window.location.reload();
                        }

                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                self.error(jqXHR, textStatus, errorThrown);
            }
        });
    };

    // ajax错误log
    self.error = function (jqXHR, textStatus, errorThrown) {
        alert("服务器响应错误");
        console.log(jqXHR.responseText);
        console.log(jqXHR.status);
        console.log(jqXHR.readyState);
        console.log(jqXHR.statusText);
        console.log(textStatus);
        console.log(errorThrown);
    };
    self.postNoForm = function (requestObject) {
        if (requestObject.formData == null || requestObject.formData == "" || typeof(requestObject.formData) == undefined) {
            alert("请给参数");
        }
        //支持异步请求
        var async1 = true;
        if (requestObject.async != null && requestObject.async != null && typeof(requestObject.async) === "boolean") {
            if (!requestObject.async) {
                async1 = false;
            }
        }
        $.ajax({
            type: "post",
            url: requestObject.url || YueXiang.LoginUrl,
            data: requestObject.formData,
            async: async1,
            headers: {
                accept: "application/json; charset=utf-8"
            },
            dataType: "json",
            success: function (response) {
                if (response) {
                    if (response.status == 200) {
                        // 请求成功之后做一些事情:首先判断方法是否存在和是否是方法类别
                        (requestObject.successCallback && typeof(requestObject.successCallback) === "function") && requestObject.successCallback(response);
                    } else if (response.status == 401) { //登录请求
                        alert("请登录后操作");
                        window.location.href = TuHao.LoginUrl;
                    } else {
                        if (requestObject.errorCallback && typeof(requestObject.errorCallback) === "function") {
                            requestObject.errorCallback(response);
                        } else {
                            alert("解析错误处理错误，请求重新请求");
                            window.location.reload();
                        }
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                self.error(jqXHR, textStatus, errorThrown);
            }
        });
    };

};

//通用日期格式化方法
//对Date的扩展，将 Date 转化为指定格式的String
//月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
//年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
//例子：
//(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
//(new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) { // author: meizz
    var o = {
        "M+": this.getMonth() + 1, // 月份
        "d+": this.getDate(), // 日
        "h+": this.getHours(), // 小时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        "S": this.getMilliseconds()
        // 毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
            .substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
                : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

//输入限制，数字
//type:0，两位小数 1,只能整数
//示例：Inputlimit($(this), 0);
function Inputlimit(obj, type) {
    if (type == 1) {
        obj.value = obj.value.replace(/\D/g, '');
    } else {
        obj.value = obj.value.replace(/[^\d.]/g, ""); //清除"数字"和"."以外的字符
        obj.value = obj.value.replace(/^\./g, ""); //验证第一个字符是数字而不是
        obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
        obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    }
}

//金额格式化
//money：金额  n:小数点位数
//示例：999,999.99
function getFormatMoney(money, n) {
    if (money == 0) {
        money = money + ".00";
    }
    else
        money = parseFloat((money + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = money.split(".")[0].split("").reverse(), r = money.split(".")[1];
    var t = "";
    for (var i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }
    money = t.split("").reverse().join("") + "." + r;
    return money;
}

///////////////////////////////////////////////////////////////////////

//检查运行环境

//pc,wechat,android,ios
function detect(ua) {
    var type = 0;
    var mobile = !!ua.match(/AppleWebKit.*Mobile.*/);
    if (mobile) {
        var wechat = ua.match(/(MicroMessenger)\/([\d\.]+)/i);
        var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
        var iphone = ua.match(/(iPhone\sOS)\s([\d_]+)/);
        if (wechat) {
            type = 1;
        } else if (android) {
            type = 2;
        } else if (iphone) {
            type = 3;
        }
    }
    return type;
}



TuHao.Layer = new function () {
    this.width = "420px";
    this.height = "240px";
    this.open = function (object) {
        layer.open({
            type: 1,
            btn: ['确定', '取消'],
            skin: 'layui-layer-rim', //加上边框
            area: [object.width || TuHao.Layer.width, object.height || TuHao.Layer.height], //宽高
            content: object.html,
            yes: function () {
                if (object.yesFunction && typeof(object.yesFunction) === "function") {
                    object.yesFunction();
                } else {
                    TuHao.Layer.alert("亲，要告诉我执行函数哦");
                }
            },
            no: function () {
                layer.closeAll();
            }
        });
    };

    this.alertReload = function (content) {
        TuHao.myAlert.addModal(content);
        TuHao.myAlert.confirm(function(){
            window.location.reload();
        });

        /*layer.closeAll();
        layer.alert(content, {
            skin: 'layui-layer-molv' //样式类名
            , closeBtn: 0
        }, function () {
            layer.closeAll();
            window.location.reload();
        });*/

    };

    this.alertReloadAll = function (content) {
        TuHao.myAlert.addModal(content);
        TuHao.myAlert.confirm(function(){
            window.parent.location.reload();
        });

        /*layer.closeAll();
        layer.alert(content, {
            skin: 'layui-layer-molv' //样式类名
            , closeBtn: 0
        }, function () {
            layer.closeAll();
            window.parent.location.reload();
        });*/
    };

    this.alert = function (content) {
        TuHao.myAlert.addModal(content);
        TuHao.myAlert.confirm();
    };

    this.validAlert = function (content) {
        TuHao.myAlert.addModal(content);
        TuHao.myAlert.confirm();
        /*layer.closeAll();
        layer.alert(content, {
            skin: 'layui-layer-molv' //样式类名
            , closeBtn: 0
        }, function () {
            layer.closeAll();
        });*/
    };

    this.alertFun = function (content,fun) {
        /*layer.closeAll();
        layer.alert(content, {
            skin: 'layui-layer-molv' //样式类名
            , closeBtn: 0
        }, fun);*/
        TuHao.myAlert.addModal(content);
        TuHao.myAlert.confirm(fun);
    };
};

//除去两边空格
String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
};

//除去左边空格
String.prototype.ltrim = function () {
    return this.replace(/(^\s*)/g, "");
};

//除去右边空格
String.prototype.rtrim = function () {
    return this.replace(/(\s*$)/g, "");
};


//判断jquery对象是否为空
$.fn.isBlank = function () {
    var $this = $(this);
    return $this == undefined || $this == null || $this == "";
};

TuHao.Tool = new function () {
    var self = this;

    self.isBlank = function (object) {
        return object == undefined || object == null || object == "";
    }

    self.trim = function(object){
        if(object == undefined || object == null || object == ""){
            return "";
        }
        return object.trim();
    }
};
